import os
import time
import keyboard
import threading
from lib.config import Config

import lib.udp_server as udp_server
import lib.tcp_server as tcp_server
import lib.log_udp_server as log_udp_server

"""
1、将TCP服务器从客户端收到的数据通过UDP服务器转发出去
2、将UDP服务器从客户端收到的数据通过TCP服务器转发出去
"""

config_param = {}
CONFIG_FILE_NAME = "./config.json"

### 监听按键，退出程序
def app_exit(tcp):
    tcp.tcp_server.close()
    udp_server.udp_server.close()
    log_udp_server.udp_server.close()
    print("Key: CTRL+X")
    os._exit(0)

### 每隔五秒读取一次参数文件
def auto_read_config_param(fn, param):
    first_read_success = False
    cp = {}
    global config_param
    while True:
        cfg = Config(fn)
        if not cfg.read_config():
            print("Config File Error!!!")
            if not first_read_success:  #系统没有运行，则退出
                os._exit(0)

        if len(cfg.get_config())>0:
            cp = cfg.get_config()
            first_read_success = True

        if not (cp==config_param):
            print("...... Update Config Param ......")
            config_param = cp.copy()
            auto_set_param()
        time.sleep(5)

def auto_update_config_run():
    td = threading.Thread(target=auto_read_config_param, args=(CONFIG_FILE_NAME, config_param))
    td.start()

def get_bool(v):
    if v is not None:
        return v
    return False

def auto_set_param():
    tcp_server.set_mavlink_enable(get_bool(config_param["SERVER"]["TCP_IMPORT_MAVLINK"]))
    tcp_server.set_auto_test_enable(get_bool(config_param["SERVER"]["TCP_SERVER_AUTO_TEST"]))
    tcp_server.set_tcp_adding(config_param["SERVER"]["TCP_SEND_AUTO_ADDING"])
    
    udp_server.set_mavlink_enable(get_bool(config_param["SERVER"]["UDP_IMPORT_MAVLINK"]))
    udp_server.set_auto_test_enable(get_bool(config_param["SERVER"]["UDP_SERVER_AUTO_TEST"]))

if __name__ == '__main__':

    print("<...TCP server, UDP server...>\n")
    print("If Exit: CTRL+X")

    sys_exit = False
    cfg = Config(CONFIG_FILE_NAME)
    if not cfg.read_config():
        print("Config File Error!!!")
        sys_exit = True
    config_param = cfg.get_config().copy()
    if len(config_param)<=0:   sys_exit = True
    if sys_exit:   os._exit(0)

    auto_set_param()
    auto_update_config_run()  #运行自动读取参数线程

    HOST = config_param["SERVER"]["HOST"]
    TCP_PORT = config_param["SERVER"]["TCP_SERVER_PORT"]
    UDP_PORT = config_param["SERVER"]["UDP_SERVER_PORT"]

    print("HOST:%s, TCP_PORT:%d, UDP_PORT:%d" % (HOST, TCP_PORT, UDP_PORT))

    tcp_sr = tcp_server.TCP_Server(HOST, TCP_PORT, 1, True)
    udp_server.udp_server_run((HOST, UDP_PORT))

    if UDP_PORT==9090:
        print("UDP server port %d invalid!!!" % (UDP_PORT, ))
        os._exit(0)
    log_udp_server.log_udp_server_run(HOST, 9090)  #开启udp信息输出服务器

    tcp_sr.run(tcp_sr)

    keyboard.add_hotkey("ctrl+x", app_exit, args=(tcp_sr,))

    while True:
        time.sleep(60)
        print("Clear Console...")
        os.system('cls')
